<?php

namespace App\Http\Controllers;

use App\Helpers\ApiResponseTrait;

class AuthController extends Controller
{
    protected $middlewareName;

    use ApiResponseTrait;
    /**
     * Create a new AuthController instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware($this->middlewareName, ['except' => ['login']]);
    }

    /**
     * Get a JWT via given credentials.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login()
    {
        $credentials = request($this->loginFields());

        $before = $this->beforeLogin();

        if(!$before['success']) {
            return $this->failed($before['error']);
        }

        if (! $token = $this->loginValidator($credentials)) {

            $this->afterLogin();

            return $this->failed('用户名或密码错误');
        }

        return $this->respondWithToken($token);
    }

    /**
     * Get the authenticated User.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function me()
    {
        $user = $this->beforeShowMe(auth()->user());
        return $this->success($user);
    }

    protected function loginValidator($credentials)
    {
        return auth()->attempt($credentials);
    }

    protected function loginFields()
    {
        return ['email', 'password'];
    }

    protected function beforeShowMe($user)
    {
        return $user;
    }

    protected function beforeLogin()
    {
        return $this->loginSuccess();
    }

    protected function loginSuccess()
    {
        return ['success'=>true];
    }

    protected function loginError($error)
    {
        return ['success'=>false,'error'=>$error];
    }

    protected function afterLogin()
    {
        return true;
    }

    /**
     * Log the user out (Invalidate the token).
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        auth()->logout();

        return $this->message('Successfully logged out');
    }

    /**
     * Refresh a token.
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function refresh()
    {
        return $this->respondWithToken(auth()->refresh());
    }

    /**
     * Get the token array structure.
     *
     * @param  string $token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    protected function respondWithToken($token,$session=null)
    {
        return $this->success([
            'access_token' => $token,
            'token_type' => 'bearer',
            'expires_in' => time() + auth()->factory()->getTTL() * 60,
            'session' => $session
        ]);
    }
}
